(function(m){
	//初始化
	navigator.getUserMedia = navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia;
	//全局stream，用于视频录制
	record={
		stream:null,
		buffer:[],
		mediaRecorder:null,
		defaultOption:{
			mimeType:"video/webm;codecs=vp8"
		}
	}
	
	STATE={
		ACTIVE:"recording",
		PAUSED:"paused",
		INACTIVE:"inactive"
	}
	
	 //默认配置
	defaultMediaStreamContrains={
		video: {
			frameRate: {min: 20},
			width: {min: 640, ideal: 1280},
			height: {min: 360, ideal: 720},
			aspectRatio: 16/9
		},
		audio: {
			echoCancellation: true,
			noiseSuppression: true,
			autoGainControl: true
		}
	}
	
	// 默认成功回调
	defaultSuccessCallBack=function(data){
		console.log(data);
	}
	
	//默认失败回调
	defaultWarnCallBack=function(msg){
		console.warn(msg);
	}
	
	//默认失败回调
	defaultErrorCallBack=function(error){
		console.error(error);
	}
	
	//生成webrtc模块
	m.webrtc =  {
		/**
		 * 获取所有设备信息
		 */
		getMediaDevices:async function(successCallBack,errorCallback){
			return await navigator.mediaDevices.enumerateDevices()
		},
		
		/**
		 * 显示本地视频
		 * @param {video document} videoDom video标签dom节点 
		 * @param {Object} mediaStreamContrains 音视频参数
		 * @param {boolean} isRecordStream 是否作为录制源
		 */
		displayCamera:async function(videoDom,mediaStreamContrains){
			mediaStreamContrains=mediaStreamContrains||defaultMediaStreamContrains;
			var mediaStream = await navigator.mediaDevices.getUserMedia(mediaStreamContrains)
			record.stream = mediaStream;
			videoDom&&(videoDom.srcObject = mediaStream);
			return mediaStream;
		},
		
		/**
		 * 显示本地桌面
		 * @param {video document} videoDom video标签dom节点 
		 * @param {Object} mediaStreamContrains 音视频参数
		 */
		displayDesktop:async function(videoDom,mediaStreamContrains){
			var audioTrack = await navigator.mediaDevices.getUserMedia({audio:defaultMediaStreamContrains.audio});
			mediaStreamContrains=mediaStreamContrains||{video:true};
			var mediaStream = await navigator.mediaDevices.getDisplayMedia(mediaStreamContrains);
			mediaStream.addTrack(audioTrack.getAudioTracks()[0]);
			record.stream = mediaStream;
			videoDom&&(videoDom.srcObject = mediaStream);
			return mediaStream;
		},
		
		/**
		 * 开始录制视频
		 * @param {Object} option
		 * @param {function} successCallBack
		 * @param {function} errorCallback
		 */
		recordStart:function(option,successCallBack,errorCallback){
			if(record.mediaRecorder&&record.mediaRecorder.state==STATE.ACTIVE){
				var errMsg = "您已在录制中！";
				errorCallback?errorCallback(errMsg):defaultErrorCallBack(errMsg);
				return;
			}

			option = option||record.defaultOption;
			if(!MediaRecorder.isTypeSupported(option.mimeType)){
				var errMsg = "浏览器不支持 "+option.mimeType;
				errorCallback?errorCallback(errMsg):defaultErrorCallBack(errMsg);
				return;
			}
			record.buffer=[];
			record.mediaRecorder = new MediaRecorder(record.stream, option);
			record.mediaRecorder.ondataavailable = function(e){
				if(e && e.data && e.data.size > 0){
					record.buffer.push(e.data);
				}
			};
			record.mediaRecorder.start(10);
			successCallBack && successCallBack(record.stream);
			
		},
		/**
		 * 暂停录制视频
		 */
		recordPause:function(){
			record.mediaRecorder && record.mediaRecorder.state==STATE.ACTIVE && record.mediaRecorder.pause();
		},
		/**
		 * 继续录制视频
		 */
		recordResume:function(){
			record.mediaRecorder && record.mediaRecorder.state==STATE.PAUSED && record.mediaRecorder.resume();
		},
		/**
		 * 停止录制视频
		 */
		recordStop:function(){
			record.stream && record.stream.getTracks().forEach(track => track.stop()) && record.stream.stop();;
			record.mediaRecorder && record.mediaRecorder.state!=STATE.INACTIVE &&record.mediaRecorder.stop();
		},
		
		/**
		 * 回放录制的视频
		 * @param {video document} videoDom
		 */
		recordReplay:function(videoDom){
			 if(!record.buffer){
				 return;
			 }
			 var blob = new Blob(record.buffer, {type: 'video/webm'});
			 videoDom.src = window.URL.createObjectURL(blob);
			 videoDom.controls = true;
			 videoDom.play();
		},
		
		/**
		 * 下载录制的视频
		 * @param {string} filename 文件名
		 * @param {number} end 下载截止点
		 */
		downloadRecord:function(filename,end){
			end = end || record.buffer.length;
			var downloadBuffer = record.buffer.slice(0,end);
			var blob = new Blob(downloadBuffer, {type: 'video/webm'});
			var url = window.URL.createObjectURL(blob);
			var a = document.createElement('a');
			a.href = url;
			a.style.display = 'none';
			a.download = filename||(new Date().getTime()+'.webm');
			a.click();
		}
	}
})(window)
	
